#pragma once
#include <sys/epoll.h>
#include <unistd.h>
#include <cstring>
#include <iostream>

namespace Epoll_module
{
    const static int default_fd = -1;
    const static int default_epoll_size = 7;

    class Epoll
    {
    public:
        Epoll() : _epoll_fd(default_fd)
        {
        }

        void Epoll_Init()
        {
            _epoll_fd = ::epoll_create(default_epoll_size); // 系统调用::
            if (_epoll_fd == -1)
            {
                std::cerr << "epoll_create error... " << strerror(errno) << std::endl;
                exit(-1);
            }
        }

        void Epoll_addevent(int sockfd, uint32_t event)
        {
            epoll_event ev;
            ev.events |= event;
            ev.data.fd = sockfd;                                      // 不是给内核的,给用户的
            int n = epoll_ctl(_epoll_fd, EPOLL_CTL_ADD, sockfd, &ev); // 添加套接字
            if (n == -1)
            {
                std::cerr << "EPOLL_CTL_ADD error... " << strerror(errno) << std::endl;
            }
        }

        int Epoll_wait(epoll_event *events, int maxevents, int timeout)
        {
            int n = epoll_wait(_epoll_fd, events, maxevents, timeout);
            return n;
        }

        void Del_event(int sockfd)
        {
            int n = epoll_ctl(_epoll_fd,EPOLL_CTL_DEL,sockfd,nullptr);
            if (n < 0)
            {
                std::cerr << "EPOLL_CTL_DEL error... " << strerror(errno) << std::endl;
            }
        }

        ~Epoll()
        {
            if (_epoll_fd > 0)
                close(_epoll_fd);
            std::cout << "epoll close" << std::endl;
        }

    private:
        int _epoll_fd;
    };
}
